<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center cart-badge">{{ cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">我的订单</h1>
        <p class="text-gray-600 mt-1">管理您的所有订单信息</p>
      </div>

      <!-- 订单状态筛选 -->
      <div class="mb-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
          <div class="flex flex-wrap gap-2">
            <button
              v-for="status in orderStatuses"
              :key="status.value"
              @click="changeOrderStatus(status.value)"
              :class="[
                'px-4 py-2 rounded-full text-sm font-medium transition-all duration-200',
                currentStatus === status.value
                  ? 'bg-primary text-white'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              ]"
            >
              {{ status.label }}
              <span v-if="status.count > 0" class="ml-1">({{ status.count }})</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="space-y-4">
        <div
          v-for="order in filteredOrders"
          :key="order.id"
          class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"
        >
          <!-- 订单头部 -->
          <div class="p-4 border-b border-gray-100 bg-gray-50">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
              <div class="flex items-center space-x-4 mb-2 md:mb-0">
                <span class="text-sm text-gray-600">订单号：</span>
                <span class="font-mono text-sm">{{ order.orderNo }}</span>
                <span class="text-sm text-gray-600">下单时间：</span>
                <span class="text-sm">{{ formatDate(order.createdAt) }}</span>
              </div>
              <div class="flex items-center space-x-4">
                <span :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
                <el-dropdown @command="(command) => handleOrderAction(command, order)">
                  <button class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-ellipsis-v"></i>
                  </button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                      <el-dropdown-item v-if="order.status === '0'" command="pay">去付款</el-dropdown-item>
                      <el-dropdown-item v-if="order.status === '2'" command="confirm">确认收货</el-dropdown-item>
                      <el-dropdown-item v-if="order.status === '3'" command="review">评价</el-dropdown-item>
                      <el-dropdown-item v-if="order.status === '4'" command="delete" divided>删除订单</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 订单商品 -->
          <div class="p-4">
            
            <div class="space-y-3">
              <div
                v-for="item in order.items || []"
                :key="item.id"
                class="flex items-center space-x-4"
              >
                <img
                  :src="item.cover"
                  :alt="item.title"
                  class="w-16 h-20 object-cover rounded cursor-pointer"
                  @click="goToBookDetail(item.id)"
                >
                <div class="flex-1">
                  <h3 class="font-medium text-gray-800 mb-1 cursor-pointer hover:text-primary" @click="goToBookDetail(item.id)">{{ item.title }}</h3>
                  <p class="text-sm text-gray-500 mb-2">作者：{{ item.author }}</p>
                  <div class="flex items-center justify-between">
                    <span class="text-primary font-bold">¥{{ item.price.toFixed(2) }}</span>
                    <span class="text-sm text-gray-600">×{{ item.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单总计和操作 -->
            <div class="mt-4 pt-4 border-t border-gray-100">
              <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <div class="text-sm text-gray-600 mb-2 md:mb-0">
                  下单数量：<span class="inline-block min-w-[1em] font-medium" style="color: #FF6B8B;">{{ getItemCount(order) }}</span>件，总计：<span class="text-xl font-bold text-primary">¥{{ order.actualAmount.toFixed(2) }}</span>
                </div>
                <div class="flex space-x-2">
                  <button
                    v-if="order.status === '0'"
                    @click="handleOrderAction('pay', order)"
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
                  >
                    立即付款
                  </button>
                  <button
                    v-if="order.status === '2'"
                    @click="handleOrderAction('confirm', order)"
                    class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
                  >
                    确认收货
                  </button>
                  <button
                    v-if="order.status === '3' && !order.reviewed"
                    @click="handleOrderAction('review', order)"
                    class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
                  >
                    评价
                  </button>
                  <button
                    v-if="order.status === '3' && order.reviewed"
                    disabled
                    class="px-4 py-2 bg-gray-300 text-gray-500 rounded-lg cursor-not-allowed"
                  >
                    已评价
                  </button>
                  <button
                    @click="handleOrderAction('detail', order)"
                    class="px-4 py-2 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    查看详情
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredOrders.length === 0" class="text-center py-16">
        <i class="fas fa-shopping-bag text-6xl text-gray-300 mb-4"></i>
        <h3 class="text-xl font-medium text-gray-500 mb-2">暂无订单</h3>
        <p class="text-gray-400 mb-6">您还没有任何订单，快去选购心仪的图书吧！</p>
        <router-link
          to="/home"
          class="inline-flex items-center px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors"
        >
          <i class="fas fa-shopping-cart mr-2"></i>
          去购物
        </router-link>
      </div>

      <!-- 分页 -->
      <div v-if="filteredOrders.length > 0" class="mt-8 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalOrders"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </main>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="订单评价"
      width="600px"
      :before-close="handleReviewDialogClose"
    >
      <div v-if="currentReviewOrder" class="space-y-6">
        <!-- 订单信息 -->
        <div class="bg-gray-50 p-4 rounded-lg">
          <h3 class="font-medium text-gray-800 mb-2">订单信息</h3>
          <p class="text-sm text-gray-600">订单号：{{ currentReviewOrder.orderNo }}</p>
          <p class="text-sm text-gray-600">下单时间：{{ formatDate(currentReviewOrder.createdAt) }}</p>
        </div>

        <!-- 商品列表 -->
        <div class="space-y-4">
          <h3 class="font-medium text-gray-800">商品清单</h3>
          <div class="border border-gray-200 rounded-lg p-4">
            <div class="space-y-3">
              <div
                v-for="item in currentReviewOrder?.items || []"
                :key="item.id"
                class="flex items-center space-x-4 py-2"
              >
                <img
                  :src="item.cover"
                  :alt="item.title"
                  class="w-12 h-16 object-cover rounded"
                >
                <div class="flex-1">
                  <h4 class="font-medium text-gray-800 text-sm">{{ item.title }}</h4>
                  <p class="text-xs text-gray-500">作者：{{ item.author }}</p>
                  <p class="text-xs text-gray-600">¥{{ item.price.toFixed(2) }} × {{ item.quantity }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 整体商品评价 -->
        <div class="space-y-4">
          <h3 class="font-medium text-gray-800">商品评价</h3>
          <div class="border border-gray-200 rounded-lg p-4">
            <!-- 评分 -->
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">商品评分</label>
              <el-rate
                v-model="reviewForm.productRating"
                :max="5"
                show-text
                :texts="['很差', '较差', '一般', '满意', '非常满意']"
              />
            </div>

            <!-- 评价内容 -->
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">商品评价</label>
              <el-input
                v-model="reviewForm.productComment"
                type="textarea"
                :rows="4"
                placeholder="请分享您对本次购买商品的整体看法..."
                maxlength="300"
                show-word-limit
              />
            </div>

            <!-- 是否匿名 -->
            <div>
              <el-checkbox v-model="reviewForm.anonymous">
                匿名评价
              </el-checkbox>
            </div>
          </div>
        </div>

        <!-- 服务评价 -->
        <div class="border-t pt-4">
          <h3 class="font-medium text-gray-800 mb-4">服务评价</h3>
          <div class="border border-gray-200 rounded-lg p-4">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">服务评分</label>
              <el-rate
                v-model="reviewForm.serviceRating"
                :max="5"
                show-text
                :texts="['很差', '较差', '一般', '满意', '非常满意']"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">服务评价</label>
              <el-input
                v-model="reviewForm.serviceComment"
                type="textarea"
                :rows="3"
                placeholder="请对我们的配送、客服等服务进行评价..."
                maxlength="200"
                show-word-limit
              />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end space-x-3">
          <el-button @click="handleReviewDialogClose">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewSubmitting">
            提交评价
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10 mt-16">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 text-center">
          <div class="text-gray-500 text-sm">
            © {{ new Date().getFullYear() }} 书香阁 版权所有
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '@/api/order.js'
import ggbondImg from '@/assets/images/ggbond.png'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const currentStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const orders = ref([])
const totalOrders = ref(0)

// 评价相关数据
const reviewDialogVisible = ref(false)
const currentReviewOrder = ref(null)
const reviewSubmitting = ref(false)
const reviewForm = reactive({
  productRating: 5,
  productComment: '',
  serviceRating: 5,
  serviceComment: '',
  anonymous: false
})

// 计算购物车数量
const cartCount = computed(() => cartStore.cartCount)

// 订单状态选项
const orderStatuses = reactive([
  { label: '全部订单', value: 'all', count: 0 },
  { label: '待付款', value: '0', count: 0 },
  { label: '待发货', value: '1', count: 0 },
  { label: '待收货', value: '2', count: 0 },
  { label: '已完成', value: '3', count: 0 },
  { label: '已取消', value: '4', count: 0 }
])

// 计算属性
const filteredOrders = computed(() => {
  return orders.value
})

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goToCart = () => {
  router.push('/cart')
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

const getStatusClass = (status) => {
  const statusClasses = {
    0: 'px-2 py-1 text-xs rounded-full bg-yellow-100 text-yellow-800', // 待支付
    1: 'px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800',     // 已支付
    2: 'px-2 py-1 text-xs rounded-full bg-purple-100 text-purple-800', // 已发货
    3: 'px-2 py-1 text-xs rounded-full bg-green-100 text-green-800',   // 已完成
    4: 'px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800'      // 已取消
  }
  return statusClasses[status] || statusClasses[0]
}

const getStatusText = (status) => {
  const statusTexts = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return statusTexts[status] || '未知状态'
}

const handleOrderAction = async (action, order) => {
  switch (action) {
    case 'detail':
      router.push(`/order/${order.id}`)
      break
    case 'pay':
      try {
        await ElMessageBox.confirm(
          `确认支付订单 ${order.orderNo}，金额 ¥${order.actualAmount.toFixed(2)} 吗？`,
          '确认支付',
          {
            confirmButtonText: '确认支付',
            cancelButtonText: '取消',
            type: 'info',
          }
        )
        // 调用支付API
        try {
          await orderAPI.payOrder(order.id, { paymentType: 1 }) // 默认使用支付宝支付
          ElMessage.success('支付成功！')
          loadOrders() // 重新加载订单列表
        } catch (error) {
          console.error('支付失败:', error)
          ElMessage.error('支付失败，请稍后重试')
        }
      } catch {
        // 用户取消支付
      }
      break
    case 'confirm':
      try {
        await ElMessageBox.confirm(
          `确认收到订单 ${order.orderNo} 的商品了吗？`,
          '确认收货',
          {
            confirmButtonText: '确认收货',
            cancelButtonText: '取消',
            type: 'info',
          }
        )
        try {
          await orderAPI.confirmOrder(order.id)
          ElMessage.success('确认收货成功！')
          loadOrders() // 重新加载订单列表
        } catch (error) {
          console.error('确认收货失败:', error)
          ElMessage.error('确认收货失败，请稍后重试')
        }
      } catch {
        // 用户取消
      }
      break
    case 'review':
      showReviewDialog(order)
      break
    case 'delete':
      try {
        await ElMessageBox.confirm(
          `确认删除订单 ${order.orderNo} 吗？此操作不可恢复。`,
          '删除订单',
          {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        // 这里可以添加删除订单的API调用
        ElMessage.success('订单删除成功！')
        loadOrders() // 重新加载订单列表
      } catch {
        // 用户取消删除
      }
      break
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadOrders()
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    }
    
    // 如果选择了特定状态
    if (currentStatus.value !== 'all') {
      params.status = currentStatus.value
    }
    
    const response = await orderAPI.getUserOrders(params)
    console.log('订单列表响应:', response) // 添加日志查看响应结构
    
    // 检查响应结构并正确处理
    if (response.data && response.data.data && response.data.data.page) {
      orders.value = response.data.data.page.records || []
      totalOrders.value = response.data.data.page.total || 0
    } else if (response.data && response.data.page) {
      orders.value = response.data.page.records || []
      totalOrders.value = response.data.page.total || 0
    } else if (response.data && Array.isArray(response.data)) {
      orders.value = response.data
      totalOrders.value = response.data.length
    } else if (response.data && response.data.records) {
      orders.value = response.data.records
      totalOrders.value = response.data.total || response.data.records.length
    } else {
      orders.value = []
      totalOrders.value = 0
      console.error('未找到预期的订单数据结构:', response)
    }
    
    // 处理订单数据，确保每个订单对象具有有效的items属性
    orders.value = orders.value.map(order => {
      console.log('原始订单数据:', order); // 添加日志查看每个订单的原始数据
      
      // 如果订单对象有bookList属性，将其设置为items
      if (order.bookList && Array.isArray(order.bookList)) {
        order.items = order.bookList;
      } 
      // 如果订单对象有orderItems属性，将其设置为items
      else if (order.orderItems && Array.isArray(order.orderItems)) {
        order.items = order.orderItems;
      }
      // 如果订单对象没有items属性或items不是数组，初始化为空数组
      else if (!order.items || !Array.isArray(order.items)) {
        order.items = [];
      }
      
      // 确保actualAmount是一个数字，便于调用toFixed方法
      if (typeof order.actualAmount !== 'number') {
        order.actualAmount = parseFloat(order.actualAmount) || 0
      }
      
      return order
    })
    
    console.log('处理后的订单数据:', orders.value); // 添加日志查看处理后的数据
    
    // 加载订单统计数据
    loadOrderStats()
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 加载订单统计数据
const loadOrderStats = async () => {
  try {
    const response = await orderAPI.getOrderStats()
    console.log('订单统计响应:', response) // 添加日志查看响应结构
    
    if (response.data && response.data.data && response.data.data.data) {
      const stats = response.data.data.data
      
      // 更新订单状态计数
      orderStatuses.forEach(status => {
        if (status.value === 'all') {
          status.count = stats.all || 0
        } else {
          status.count = stats[getStatusName(status.value)] || 0
        }
      })
    } else if (response.data && response.data.data) {
      const stats = response.data.data
      
      // 更新订单状态计数
      orderStatuses.forEach(status => {
        if (status.value === 'all') {
          status.count = stats.all || 0
        } else {
          status.count = stats[getStatusName(status.value)] || 0
        }
      })
    } else {
      console.error('未找到预期的订单统计数据结构:', response)
    }
  } catch (error) {
    console.error('加载订单统计数据失败:', error)
  }
}

// 获取状态名称
const getStatusName = (status) => {
  const statusNames = {
    '0': 'pending',
    '1': 'paid',
    '2': 'shipped',
    '3': 'completed',
    '4': 'cancelled'
  }
  return statusNames[status] || 'all'
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      // 已经在订单页面，不需要跳转
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 显示评价弹窗
const showReviewDialog = (order) => {
  currentReviewOrder.value = order
  // 初始化评价表单
  reviewForm.productRating = 5
  reviewForm.productComment = ''
  reviewForm.serviceRating = 5
  reviewForm.serviceComment = ''
  reviewForm.anonymous = false
  reviewDialogVisible.value = true
}

// 关闭评价弹窗
const handleReviewDialogClose = () => {
  reviewDialogVisible.value = false
  currentReviewOrder.value = null
  reviewForm.productRating = 5
  reviewForm.productComment = ''
  reviewForm.serviceRating = 5
  reviewForm.serviceComment = ''
  reviewForm.anonymous = false
}

// 提交评价
const submitReview = async () => {
  // 验证评价内容
  if (!reviewForm.productComment.trim()) {
    ElMessage.warning('请填写商品评价内容')
    return
  }

  try {
    reviewSubmitting.value = true

    // 模拟提交评价到服务器
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage.success('评价提交成功！感谢您的反馈')
    
    // 重新加载订单列表
    loadOrders()
    
    handleReviewDialogClose()

  } catch (error) {
    ElMessage.error('评价提交失败，请稍后重试')
  } finally {
    reviewSubmitting.value = false
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 切换订单状态筛选
const changeOrderStatus = (status) => {
  currentStatus.value = status
  currentPage.value = 1
  loadOrders()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadOrders()
})

// 在script setup部分添加这个方法
const getItemCount = (order) => {
  // 优先使用后端计算的商品数量
  if (typeof order.itemCount === 'number') {
    return order.itemCount;
  }

  // 如果有totalGoodsCount字段
  if (typeof order.totalGoodsCount === 'number') {
    return order.totalGoodsCount;
  }

  // 检查orderItems数组，计算quantity总和
  if (order.orderItems && Array.isArray(order.orderItems)) {
    return order.orderItems.reduce((total, item) => total + (item.quantity || 0), 0);
  }

  // 检查items数组，计算quantity总和
  if (order.items && Array.isArray(order.items)) {
    return order.items.reduce((total, item) => total + (item.quantity || 0), 0);
  }

  // 检查bookList数组，计算quantity总和
  if (order.bookList && Array.isArray(order.bookList)) {
    return order.bookList.reduce((total, item) => total + (item.quantity || 0), 0);
  }

  // 返回默认值
  return 0;
}
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.hover\:border-primary:hover {
  border-color: #FF6B8B !important;
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.bg-primary-dark {
  background-color: #E55A7A !important;
}

.hover\:bg-primary-dark:hover {
  background-color: #E55A7A !important;
}

.cart-badge {
  z-index: 10;
  transform: translate(25%, -25%);
  min-width: 18px;
  height: 18px;
}

/* 订单卡片样式 */
.order-card {
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 状态筛选按钮样式 */
.status-filter-btn {
  transition: all 0.2s ease;
}

.status-filter-btn:hover {
  transform: translateY(-1px);
}

/* 订单商品图片悬停效果 */
.order-item-image {
  transition: all 0.3s ease;
}

.order-item-image:hover {
  transform: scale(1.05);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .order-actions {
    flex-direction: column;
    gap: 0.5rem;
  }

  .order-actions button {
    width: 100%;
  }
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
